import gradio as gr
import cv2 
import matplotlib.pyplot as plt
import numpy as np
from pinecone import Pinecone
import logging
import pickle
# 配置logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')

#初始化pinecone
pc = Pinecone(api_key="2183433c-f83f-4c83-9e03-6a4ae634ecfa")

#连接索引
index_name = "mnist-index"
index = pc.Index(index_name)
logging.info(f"已成功连接到索引 '{index_name}'。")

def predict_digit(image):  
    image = cv2.resize(image, (8, 8))  # 假设Pinecone索引的向量维度是64（8x8）  
    image_vector = image.flatten().tolist()  # 将图像转换为向量  
  
    max_retries = 3  
    for attempt in range(max_retries):  
        try:  
            query_result = index.query(  
                vector=image_vector,  
                top_k=1,  # 只取最近的1个结果  
                include_metadata=True  
            )  
            break  
        except Exception as e:  
            if attempt < max_retries - 1:  
                logging.warning(f"查询失败，正在重试（第{attempt+1}次）: {str(e)}")  
            else:  
                logging.error(f"查询失败，已达到最大重试次数: {str(e)}")  
                return "查询失败" 

#构建Gradio界面
gr.Interface(fn=predict_digit, inputs='sketchpad', outputs='text').launch()